function MergeRinex(filenIn1,cellrange,filenOut)
%MergeRinex3 - RINEX file merging
%
%       MergeRinex(FilenIn1,cellRange,FilenOut)
%
% This function merges RINEX2 or RINEX3 starting from the first file 
% Filenin1 to the last file on the basis of the variable part of the 
% filenames encoded in cellRange. 
% For example, if Rinex2 files are considered, FilenIn1 is
%           'MSEL123k.21o'
% and 
%           cellRange = {'k', 'l', 'm'}, 
% these files are merged leading to the outputfile FilenOut:
%           'MSEL123k.21o'
%           'MSEL123l.21o'
%           'MSEL123m.21o'
% (note: cellRange(k) is the 8th character of the k-th filename)
% If Rinex3 files are considered, FilenIn1 is 
%           'MSEL00ITA_R_20211230900_01H_30S_MO.rnx'
% and 
%           cellRange = {'0900', '1000', '1100'}, 
% these files are merged leading to the outputfile FilenOut:
%           'MSEL00ITA_R_20211230900_01H_30S_MO.rnx'
%           'MSEL00ITA_R_20211231000_01H_30S_MO.rnx'
%           'MSEL00ITA_R_20211231100_01H_30S_MO.rnx'
% (note: the 4-length string cellRange(k) is the section of characters 20-23
% of the k-th filename)
%
% This function requires the external package:
%   - GFZRNX (windows10 64 bit or Linux 64 bit placed on c:\GNSS\RGFZRNX or
%     /mnt/c/GNSS/GFZRNX/ directory respectively. If a different version 
%     and/or a different folder should be used, the function must be edited 
%     accordingly).
%     Download link: https://gnss.gfz-potsdam.de/services/gfzrnx 
%     (registration is necessary)
%
%       MergeRinex(filenin1,cellrange,filenout)
%
%  See also Rinex32Rinex2, StationNameEdit, ExtraRinex3. 

% G. Teza, 2023

if ispc
    commConv = '"c:\GNSS\GFZRNX\gfzrnx_1.16-8154_win10_64.exe" ';
elseif isunix
    commConv = '/mnt/c/GNSS/GFZRNX/gfzrnx_1.16-8154_lx64 ';  
else
    error('Unsuitable operating system');
end

[foldernam,filenam,ext] = fileparts(filenIn1);

if strcmpi(ext,'.rnx')
    fileco1 = filenam(1:19);
    fileco2 = filenam(24:end);
else
    fileco1 = filenam(1:7);
    fileco2 = '';
end

if ~isempty(foldernam)
    [foldernamO,~,~] = fileparts(filenOut);
    if ~strcmpi(foldernam,foldernamO)
        filenOut = fullfile(foldernam,filenOut);
    end
end

nf = numel(cellrange);

strCommandIn = '';
for k = 1:nf
    strk = cellrange{k};
    filek = [fileco1 strk fileco2 ext];
    filek = fullfile(foldernam,filek);
    strCommandIn = [strCommandIn filek ' ']; %#ok<AGROW> 
end

% Rinex files merging:
strCommandCompl = [commConv '-finp ' strCommandIn '-fout ' filenOut ' -kv'];

system(strCommandCompl); 